import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormDigit, ProFormSelect,
  ProFormText,
  ProTable
} from "@ant-design/pro-components";
import {Button, Form, message, Modal, Popconfirm, Tooltip} from "antd";
import React, {useRef, useState} from "react";
import {CopyOutlined, SettingFilled, SwapOutlined, UnorderedListOutlined} from "@ant-design/icons";
import {globalApi, globalLoadTableApi, globalLoadTableApiCode, handleGloblApi} from "@/services/admin-api/globalApi";
import {ProductInventory} from "@/pages/Config/Product";
import {useAccess} from "umi";

export const productSelect = await globalApi('/product/select', {})
export const storeSelect = await globalApi('/store/select', {})

export default () => {
  const access = useAccess()

  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [modalChangeInventoryOpen, handleChangeInventoryModalOpen] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [row, setRow] = useState<ProductInventory>()

  // <ProFormDependency name={}

  const inventoryColumns: ProColumns<ProductInventory>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: 'ID', dataIndex: 'inventoryId', valueType: 'digit', hideInSearch: true},
    {
      title: '产品',
      dataIndex: 'productId',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {options: productSelect.data, showSearch: true}
    },
    {title: '产品ID', dataIndex: 'productId', valueType: 'digit', hideInSearch: true},
    {title: '产品名称', dataIndex: 'productName', valueType: 'text', hideInSearch: true},
    // {title: '产品价格', dataIndex: 'productPrice', valueType: 'money', hideInSearch: true},
    // {title: '产品总价', dataIndex: 'productTotalPrice', valueType: 'money', hideInSearch: true},
    {
      title: '规格',
      dataIndex: 'productSpecificationId',
      valueType: 'select',
      hideInTable: true,
      dependencies: ['productId'],
      request: async (param) => {
        console.log('param = ', param)
        if (param.productId) {
          const r = await globalApi('/product/specificationSelect', param)
          return r.data
        }
        return []
      },
      fieldProps: {showSearch: true,}
    },
    {title: '规格ID', dataIndex: 'productSpecificationId', valueType: 'digit', hideInSearch: true},
    {title: '规格', dataIndex: 'productSpecification', valueType: 'text', hideInSearch: true},
    {
      title: '店铺',
      dataIndex: 'storeId',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {options: storeSelect.data, showSearch: true}
    },
    {title: '店铺ID', dataIndex: 'storeId', valueType: 'digit', hideInSearch: true},
    {title: '店铺名称', dataIndex: 'storeName', valueType: 'text', hideInSearch: true},
    {title: '库存', dataIndex: 'productInventory', valueType: 'digit', hideInSearch: true},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Tooltip key={'change_' + record.inventoryId} title={"出入库"}>
          <Button
            size="small" icon={<SwapOutlined/>} type="primary"
            onClick={async () => {
              form.setFieldsValue({...record})
              handleChangeInventoryModalOpen(true)
            }}
          />
        </Tooltip>,
        <Tooltip key={'list_product_inventory' + record.inventoryId} title={"出入库记录"}>
          <Button
            size="small" icon={<UnorderedListOutlined/>} type="primary"
            onClick={async () => {
              setRow({...record})
              setIsModalOpen(true)
            }}
          /></Tooltip>,
      ],
      valueType: 'option',
    },
  ];

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<ProductInventory>
      columns={inventoryColumns} actionRef={actionRef}
      search={{span: 4}}
      request={async (param) => globalLoadTableApiCode('/product/productInventoryTable', 'inventory:list:search', access, param)}
      rowKey={(record) => record.inventoryId}
      headerTitle={<Tooltip title={"将所有未入库的产品规格入库并设置库存为0"}>
        <Popconfirm
          title="所有产品规格所有店铺库存初始化"
          description="确认执行这个任务，不可撤销？"
          onConfirm={() => {
            handleGloblApi('/product/refreshAllProductInventory', {})
            actionRef.current?.reload()
          }}
          onCancel={() => {

          }}
          okText="Yes"
          cancelText="No"
        >
          <Button icon={<CopyOutlined/>} type={"primary"}></Button>
        </Popconfirm> </Tooltip>}
      columnsState={{
        defaultValue: {
          inventoryId: {show: false},
          productId: {show: false},
          productSpecificationId: {show: false},
          storeId: {show: false},
          delFlag: {show: false},
          createUserId: {show: false},
          updateUserId: {show: false}
        }
      }}/>


    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalChangeInventoryOpen} onOpenChange={handleChangeInventoryModalOpen}
      form={form}
      onFinish={async (value) => {
        console.log('value = ', value)
        let success = await handleGloblApi('/product/productChanegInventory', value)

        if (success) {
          actionRef.current?.reload()
          return true
        }

      }}
    >
      <ProFormDigit label="inventoryId" name="inventoryId" hidden/>
      <ProFormDigit label="productId" name="productId" hidden/>
      <ProFormText label="productName" name="productName" hidden/>
      <ProFormDigit label="productSpecificationId" name="productSpecificationId" hidden/>
      <ProFormText label="productSpecification" name="productSpecification" hidden/>
      <ProFormDigit label="storeId" name="storeId" hidden/>
      <ProFormText label="storeName" name="storeName" hidden/>

      <ProFormSelect
        rules={[{required: true}]} label={"操作类型"} name={"operateType"}
        options={[{label: '出库', value: 0}, {label: '入库', value: 1}]}/>

      <ProFormDigit
        min={1} label="数量" rules={[{required: true}]} name="changeInventory"/>

      <ProFormText label="备注" rules={[{required: true}]} name="remark"/>

    </ModalForm>

    <Modal
      destroyOnClose width={1200} open={isModalOpen} onOk={() => {
      setIsModalOpen(false)
    }} onCancel={() => {
      setIsModalOpen(false)
    }}>
      <ProTable
        search={false} columns={[
        // {title: '', valueType: 'indexBorder'},
        {title: 'ID', dataIndex: 'productInventoryRecordId', valueType: 'digit', hideInSearch: true},
        {title: '库存ID', dataIndex: 'inventoryId', valueType: 'digit', hideInSearch: true},
        {title: '产品ID', dataIndex: 'productId', valueType: 'digit', hideInSearch: true},
        {title: '产品名称', dataIndex: 'productName', valueType: 'text', hideInSearch: true},
        // {title: '产品价格', dataIndex: 'productPrice', valueType: 'money', hideInSearch: true},
        // {title: '规格ID', dataIndex: 'productSpecificationId', valueType: 'digit', hideInSearch: true},
        {title: '规格', dataIndex: 'productSpecification', valueType: 'text', hideInSearch: true},
        {title: '店铺ID', dataIndex: 'storeId', valueType: 'digit', hideInSearch: true},
        {title: '店铺名称', dataIndex: 'storeName', valueType: 'text', hideInSearch: true},
        {title: '改变前', dataIndex: 'beforeInventory', valueType: 'digit', hideInSearch: true},
        {title: '变动库存', dataIndex: 'changeInventory', valueType: 'digit', hideInSearch: true},
        {title: '最新库存', dataIndex: 'afterInventory', valueType: 'digit', hideInSearch: true},
        {title: '订单ID', dataIndex: 'orderId', valueType: 'text', hideInSearch: true},
        {title: '备注', dataIndex: 'remark', valueType: 'text', hideInSearch: true},
        {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
        {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
        {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
        {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
        {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
        {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
      ]} rowKey={(record) => record.productInventoryRecordId}
        columnsState={{
          defaultValue: {
            productInventoryRecordId: {show: false},
            inventoryId: {show: false},
            productId: {show: false},
            productSpecificationId: {show: false},
            storeId: {show: false},
            delFlag: {show: false},
            createUserId: {show: false},
            updateUserId: {show: false}
          }
        }} params={{inventoryId: row?.inventoryId}}
        request={async (param) => globalLoadTableApi('/product/inventoryRecordTable', param)}/>

    </Modal>

  </PageContainer>
}
